from fastapi import FastAPI, APIRouter, UploadFile, File
import os
from fastapi.responses import JSONResponse

upload = APIRouter()

file_dir_path = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'file_info')
print(file_dir_path)


@upload.post('/file')
async def upload_file(file: UploadFile = File(...)):
    """
    上传文件接口【文件上传到file_info文件夹中】
    """
    content = await file.read()
    print(file.filename)
    file_path = os.path.join(file_dir_path, file.filename)
    if os.path.exists(file_dir_path):
        with open(file_path, 'wb') as f:
            f.write(content)
        return JSONResponse(content={
            "filename": file.filename,
            "size": len(content)
        })
    else:
        os.mkdir(file_dir_path)
